package com.example.adouble.cehuamenu.ui.activity;

import android.Manifest;
import android.app.ActivityOptions;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.adouble.cehuamenu.R;
import com.example.adouble.cehuamenu.mode.Book;
import com.example.adouble.cehuamenu.mode.User;
import com.example.adouble.cehuamenu.ui.adapter.BookAdapter;
import com.example.adouble.cehuamenu.util.ToastUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends BaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    CircleImageView uhead;

    @BindView(R.id.drawerLayout)
    DrawerLayout drawerLayout;

    @BindView(R.id.navigationView)
    NavigationView navigationView;

    private List<View> views;

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;

    @BindView(R.id.tvSearch)
    TextView tvSearch;

    TextView username;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private BookAdapter adapter;
    private SharedPreferences sp;
    private String local, id;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取手机权限
        int permission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }

        sp = getSharedPreferences("login", MODE_PRIVATE);
        local = sp.getString("uname", "登录");
        id = sp.getString("id", "空");

        initView();
        bindListener();
        select();

        handler.sendEmptyMessageAtTime(2, 1000);
    }

    //获取手机权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    /**
     * 初始化视图
     */
    private void initView() {
        View headerView = navigationView.getHeaderView(0);//获取头布局0
        uhead = headerView.findViewById(R.id.icon);
        username = headerView.findViewById(R.id.tv_name);

        //设置用户名
        username.setText(local);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    /**
     * 绑定控件
     */
    private void bindListener() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (drawerLayout.isDrawerOpen(navigationView)) {
                    drawerLayout.closeDrawer(navigationView);
                } else {
                    drawerLayout.openDrawer(navigationView);
                }
            }
        });

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {

                switch (item.getItemId()) {
                    case R.id.dongtai:
                        Intent intent = new Intent(MainActivity.this, DongTaiActivity.class);
                        startActivity(intent);
                        break;
                    case R.id.news:
                        Toast.makeText(MainActivity.this, item.getTitle().toString(), Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.book:
                        Intent intent1 = new Intent(MainActivity.this, MyBookActivity.class);
                        startActivity(intent1);
                        break;
                }
                drawerLayout.closeDrawer(navigationView);
                return true;
            }
        });

        //登录
        username.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (local.equals("登录")) {
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(MainActivity.this, InfoActivity.class);
                    startActivity(intent);
                }
            }
        });

        //热门图书下拉刷新
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                handler.sendEmptyMessageAtTime(1, 2000);
                ToastUtils.show("刷新成功");
            }
        });
    }


    /**
     * 搜索图书界面
     *
     * @param view
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void search(View view) {
        Intent intent = new Intent(MainActivity.this, SearchActivity.class);
        startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, tvSearch, "srh").toBundle());
    }

    /**
     * 刷新页面更新数据
     */
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    select();
                    if (swipeRefreshLayout.isRefreshing()) {
                        //关闭刷新动画
                        swipeRefreshLayout.setRefreshing(false);
                    }
                    break;
                case 2:
                    if (id.equals("空")) {
                        uhead.setImageResource(R.drawable.a5);
                    } else {
                        BmobQuery<User> bmobQuery = new BmobQuery<>();
                        bmobQuery.getObject(id, new QueryListener<User>() {
                            @Override
                            public void done(User user, BmobException e) {
                                Glide.with(MainActivity.this).load(user.getPath()).into(uhead);
                            }
                        });
                    }
                    break;
            }
        }
    };

    /**
     * 查询图书数据
     */
    public void select() {
        BmobQuery<Book> bmobQuery = new BmobQuery<>();
        bmobQuery.order("-b_pageviews");
        bmobQuery.findObjects(new FindListener<Book>() {
            @Override
            public void done(final List<Book> list, BmobException e) {
                if (e == null) {
                    adapter = new BookAdapter(MainActivity.this, list);
                    recyclerView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    adapter.setItemOnClickListener(new BookAdapter.ItemClickListener() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Intent intent = new Intent(MainActivity.this, DetailActivity.class);
                            intent.putExtra("bname", list.get(position).getB_name());
                            startActivity(intent);
                        }
                    });
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        id = sp.getString("id", "空");
        local = sp.getString("uname", "登录");
        username.setText(local);
        if (id.equals("空")) {
            uhead.setImageResource(R.drawable.a5);
        } else {
            BmobQuery<User> bmobQuery = new BmobQuery<>();
            bmobQuery.getObject(id, new QueryListener<User>() {
                @Override
                public void done(User user, BmobException e) {
                    Glide.with(MainActivity.this).load(user.getPath()).into(uhead);
                }
            });
        }
    }

//    /**
//     * 判断recyclerView是否已到底部
//     * @param recyclerView
//     * @return
//     */
//    public static boolean isBottom(RecyclerView recyclerView) {
//        if (recyclerView == null) return false;
//        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
//                >= recyclerView.computeVerticalScrollRange())
//            return true;
//        return false;
//    }

}
